import React, { useEffect, useRef } from 'react';
import { SimpleAffineEditor, EditorContainer } from '@blocksuite/editor';
import { Workspace, Schema, Page, Text } from '@blocksuite/store';
import { AffineSchemas } from '@blocksuite/blocks/models';

import '@blocksuite/editor/themes/affine.css';
import { Button } from '@nextui-org/react';

const BlockSuite: React.FC = () => {
  const simpleAffineEditorRef = useRef<HTMLDivElement>(null);
  const blockSuiteEditorRef = useRef<EditorContainer | null>(null);
  const workspaceRef = useRef<Workspace | null>(null);

  useEffect(() => {
    if (
      simpleAffineEditorRef.current &&
      simpleAffineEditorRef.current.childNodes.length === 0
    ) {
      initEditor();
      return () => {
        console.log('come in');
        simpleAffineEditorRef.current?.removeChild(
          blockSuiteEditorRef.current!
        );
      };
    }
  }, []);

  const initEditor = async () => {
    const schema = new Schema();

    workspaceRef.current = new Workspace({
      id: 'test-workspace',
      schema,
    });

    schema.register(AffineSchemas);

    const page: Page = workspaceRef.current.createPage({
      id: 'page0',
    });

    //配置
    page.clear();
    await page.waitForLoaded();
    // Add page block and surface block at root level
    const pageBlockId = page.addBlock('affine:page', {
      title: new Text('My New Page'),
    });
    console.log('pageBlockId', pageBlockId);
    page.updateBlock(page.getBlockById(pageBlockId)!, {title: new Text('aaa')});
    page.addBlock('affine:surface', {}, pageBlockId);

    // Add note block inside page block
    //在页面内添加注释块
    const noteId = page.addBlock('affine:note', {}, pageBlockId);
    // Add paragraph block inside note block
    // 在Note Block中添加段落块
    page.addBlock('affine:paragraph', {}, noteId);
    page.resetHistory();

    blockSuiteEditorRef.current = new EditorContainer();
    blockSuiteEditorRef.current.page = page;
    simpleAffineEditorRef.current!.appendChild(blockSuiteEditorRef.current);
  };

  const handleBtnClick = () => {
    console.log(
      'test',
      blockSuiteEditorRef.current!.page.getBlockByFlavour('affine:paragraph')[0].id
    );
    console.log('workspaceRef.current?.doc.toJSON()', workspaceRef.current?.doc.toJSON());
  };
  return (
    <>
      <div ref={simpleAffineEditorRef} id="editor-container"></div>
      <Button color="primary" onClick={handleBtnClick}>
        test
      </Button>
    </>
  );
};

export default BlockSuite;
